import logging
import datetime
import os
from typing import Union
from pathlib import Path


def get_logger(save_prefix: Union[Path, str], name: str = None):
    if name is None:
        name = datetime.datetime.now().strftime("%Y-%b-%d-%H-%M-%S")
    logger = logging.getLogger(name)
    logger.setLevel(logging.INFO)

    if os.path.exists(save_prefix) is False:
        os.mkdir(save_prefix)
    # .log 保存日志
    file_handler = logging.FileHandler(os.path.join(save_prefix, f'{name}.log'))
    logger.addHandler(file_handler)
    # 控制台输出日志
    console_handler = logging.StreamHandler()
    logger.addHandler(console_handler)
    # 设置日志格式
    formatter = logging.Formatter(fmt='%(asctime)s - %(levelname)s:    %(message)s',
                                  datefmt='%Y-%m-%d %H:%M:%S')
    console_handler.setFormatter(formatter)
    file_handler.setFormatter(formatter)
    return logger
